package com.zdzx.controller.web;

import java.time.LocalDateTime;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zdzx.base.common.util.RedisUtil;
import com.zdzx.base.common.util.UserInfoUtil;
import com.zdzx.common.result.PageInfo;
import com.zdzx.common.result.PageUtil;
import com.zdzx.common.result.Result;
import com.zdzx.common.result.ResultCode;
import com.zdzx.common.result.ResultUtil;
import com.zdzx.common.util.Md5Util;
import com.zdzx.mapper.ArticleMapper;
import com.zdzx.mapper.CourseCollectionMapper;
import com.zdzx.mapper.CourseMapper;
import com.zdzx.mapper.DicMapper;
import com.zdzx.mapper.SystemConfigMapper;
import com.zdzx.mapper.TransactionRecordMapper;
import com.zdzx.mapper.UserMapper;
import com.zdzx.model.dic.FileType;
import com.zdzx.model.dic.SystemConfigType;
import com.zdzx.model.service.base.param.ChangeInfo;
import com.zdzx.model.service.base.param.ChangePassword;
import com.zdzx.model.service.base.param.EditUser;
import com.zdzx.model.service.base.result.UserInfo;
import com.zdzx.model.service.base.vo.Dic;
import com.zdzx.model.service.base.vo.User;
import com.zdzx.model.service.content.param.UserCollectionCourse;
import com.zdzx.model.service.content.param.UserTransactionRecord;
import com.zdzx.model.service.content.param.UserWatchArticle;
import com.zdzx.model.service.content.param.UserWatchCourse;
import com.zdzx.model.service.content.vo.Course;
import com.zdzx.model.service.content.vo.CourseCollection;
import com.zdzx.service.OSSService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@Api(tags = "web个人中心")
@RestController()
@RequestMapping("/web")
public class WebUserController {

	@Autowired
	private RedisUtil redisUtil;

	@Autowired
	private UserMapper userMapper;
	@Autowired
	private CourseMapper courseMapper;
	@Autowired
	private ArticleMapper articleMapper;
	@Autowired
	private CourseCollectionMapper courseCollectionMapper;
	@Autowired
	private TransactionRecordMapper transactionRecordMapper;
	@Autowired
	private SystemConfigMapper systemConfigMapper;
	@Autowired
	private OSSService ossService;
	@Autowired
	private DicMapper dicMapper;
	
	@ApiOperation(value = "修改密码", notes = "")
	@PutMapping("/user/changePassword")
	public Result<String> changePassword(@RequestBody ChangePassword changePassword,HttpServletRequest request){
		UserInfo loginInfo = UserInfoUtil.getLoginInfo(UserInfo.class, redisUtil, request);
		if (loginInfo == null) {
			return ResultUtil.data(ResultCode.NOT_LOGIN.getCode(), ResultCode.NOT_LOGIN.getMes(), null);
		}
		if(!Md5Util.hash(changePassword.getOldPassword()).equals(loginInfo.getPassword())) {
			return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "原密码不正确", null);
		}else if(!changePassword.getAgainPassword().equals(changePassword.getNewPassword())) {
			return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(),"两次密码不一致", null);
		}else {
			User entity=new User();
			entity.setId(loginInfo.getId());
			entity.setPassword(Md5Util.hash(changePassword.getAgainPassword()));
			int rows = userMapper.updateById(entity);
			return ResultUtil.data(rows>0?ResultCode.RESULT_SUCCESS.getCode():ResultCode.RESULT_ERROR.getCode(),rows>0?"修改成功":"修改失败", null);
		}
	}
	@ApiOperation(value = "用户信息", notes = "")
	@GetMapping("/user/info")
	public Result<UserInfo> info(HttpServletRequest request){
		UserInfo loginInfo = UserInfoUtil.getLoginInfo(UserInfo.class, redisUtil, request);
		if(loginInfo==null)
			return ResultUtil.data(ResultCode.NOT_LOGIN.getCode(), ResultCode.NOT_LOGIN.getMes(), null);
		Integer count=courseMapper.userStudyTimeCount(loginInfo.getId(),null);
		Integer articleCount=articleMapper.userArticleStudyTimeCount(loginInfo.getId());
		loginInfo.setStudyTimeCount(count==null?0:count);
		loginInfo.setArticleStudyTimeCount(articleCount==null?0:articleCount);
		return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), null, loginInfo);
	}
	@ApiOperation(value = "修改用户信息", notes = "")
	@PutMapping("/user/info")
	public Result<String> changeInfo(@RequestBody ChangeInfo changeInfo,HttpServletRequest request){
		UserInfo loginInfo = UserInfoUtil.getLoginInfo(UserInfo.class, redisUtil, request);
		if(loginInfo==null) {
			return ResultUtil.data(ResultCode.NOT_LOGIN.getCode(),ResultCode.NOT_LOGIN.getMes(), null);
		}
		EditUser editUser=new EditUser();
		BeanUtils.copyProperties(changeInfo, editUser);
		editUser.setId(loginInfo.getId());
		
		User user=new User();
		BeanUtils.copyProperties(editUser, user);
		//user.setHeadUrl(user.getHeadUrl()!=null?user.getHeadUrl().replace(SystemConfig.ossIp, ""):"",false);
		int rows = userMapper.updateById(user);
		User newUserInfo = userMapper.selectById(user.getId());
		UserInfo userInfo = new UserInfo();
	    //userInfo.setResouces(functions);
		BeanUtils.copyProperties(newUserInfo, userInfo);
		userInfo.setFrom(loginInfo.getFrom());
		UserInfoUtil.updateLogInfo(userInfo,redisUtil, request);
		return ResultUtil.data(rows>0?ResultCode.RESULT_SUCCESS.getCode():ResultCode.RESULT_ERROR.getCode(), null, null);
	}
	
	
	@ApiOperation(value = "用户已学课程", notes = "")
	@GetMapping("/user/watchCourse")
	public Result<PageInfo<UserWatchCourse>> watchCourse(
			@ApiParam("") @RequestParam(value="tenantId", required = false) String tenantId,
			@ApiParam("") @RequestParam(value = "pageNum", required = false) Integer pageNum,
			@ApiParam("") @RequestParam(value = "pageSize", required = false) Integer pageSize,
			HttpServletRequest request){
		UserInfo loginInfo = UserInfoUtil.getLoginInfo(UserInfo.class, redisUtil, request);
		if(loginInfo==null) {
			return ResultUtil.data(ResultCode.NOT_LOGIN.getCode(),ResultCode.NOT_LOGIN.getMes(), null);
		}
		if(pageNum==null||pageSize==null) {
			pageNum=1;
			pageSize=10;
		}
		Page<UserWatchCourse> page=new Page<UserWatchCourse>(pageNum,pageSize);
		if(StringUtils.isEmpty(tenantId)) {
			tenantId="00000000";
		}
		IPage<UserWatchCourse> info = courseMapper.userWatchCourse(page,loginInfo.getId(),tenantId,null,null,"1");
		List<UserWatchCourse> records = info.getRecords();
		if(info.getRecords().size()>0) {
			for (int i=0;i<info.getRecords().size();i++) {
				UserWatchCourse userWatchCourse = records.get(i);
				List<UserWatchCourse> userWatchCourseChildren = courseMapper.userWatchCourseChildren(userWatchCourse.getId(),loginInfo.getId());
				userWatchCourse.setChildren(userWatchCourseChildren);
				records.set(i, userWatchCourse);
			}
		}
		Integer count=courseMapper.userStudyTimeCount(loginInfo.getId(),tenantId);
		info.setRecords(records);
		PageInfo<UserWatchCourse> data = PageUtil.data(info.getPages(),count==null?0:count.longValue(), info.getTotal(), info.getRecords());
		return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(),null,data);
	}
	
	
	@ApiOperation(value = "用户已学文章", notes = "")
	@GetMapping("/user/watchArticle")
	public Result<PageInfo<UserWatchArticle>> watchArticle(
			@ApiParam("") @RequestParam(value = "pageNum", required = false) Integer pageNum,
			@ApiParam("") @RequestParam(value = "pageSize", required = false) Integer pageSize,
			HttpServletRequest request){
		UserInfo loginInfo = UserInfoUtil.getLoginInfo(UserInfo.class, redisUtil, request);
		if(loginInfo==null) {
			return ResultUtil.data(ResultCode.NOT_LOGIN.getCode(),ResultCode.NOT_LOGIN.getMes(), null);
		}
		if(pageNum==null||pageSize==null) {
			pageNum=1;
			pageSize=10;
		}
		Page<UserWatchArticle> page=new Page<>(pageNum,pageSize);
		IPage<UserWatchArticle> info = courseMapper.userWatchArticle(page,loginInfo.getId());
		List<UserWatchArticle> records = info.getRecords();
		if(records.size()>0) {
			QueryWrapper<Dic> queryWrapper=new QueryWrapper<Dic>();
			queryWrapper.eq("`type`", "article");
			List<Dic> selectList = dicMapper.selectList(queryWrapper);
			for(int i=0;i<records.size();i++) {
				for(int j=0;j<selectList.size();j++) {
					if(records.get(i).getType().equals(selectList.get(j).getCode())) {
						records.get(i).setType(selectList.get(j).getValue());
					}
				}
			}
		}
		PageInfo<UserWatchArticle> data = PageUtil.data(info.getPages(), info.getCurrent(), info.getTotal(), records);
		return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(),null,data);
	}
	
	
	@ApiOperation(value = "用户收藏课程", notes = "")
	@GetMapping("/user/collectionCourse")
	public Result<PageInfo<UserCollectionCourse>> collectionCourse(
			@ApiParam("") @RequestParam(value = "pageNum", required = false) Integer pageNum,
			@ApiParam("") @RequestParam(value = "pageSize", required = false) Integer pageSize,
			HttpServletRequest request){
		UserInfo loginInfo = UserInfoUtil.getLoginInfo(UserInfo.class, redisUtil, request);
		if(loginInfo==null) {
			return ResultUtil.data(ResultCode.NOT_LOGIN.getCode(),ResultCode.NOT_LOGIN.getMes(), null);
		}
		IPage<UserCollectionCourse> page=new Page<UserCollectionCourse>();
		IPage<UserCollectionCourse> info = courseMapper.userCollectionCourse(page,loginInfo.getId());
		PageInfo<UserCollectionCourse> data = PageUtil.data(info.getPages(), info.getCurrent(), info.getTotal(), info.getRecords());
		return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(),null,data);
	}
	
	
	
	
	@ApiOperation(value = "用户收藏课程", notes = "")
	@PostMapping("/user/collectionCourse/{courseId}/{collection}")
	public Result<String> setCollectionCourse(@PathVariable("courseId")String courseId,
			@PathVariable("collection")String collection,HttpServletRequest request){
		UserInfo loginInfo = UserInfoUtil.getLoginInfo(UserInfo.class, redisUtil, request);
		if(loginInfo==null) {
			return ResultUtil.data(ResultCode.NOT_LOGIN.getCode(), ResultCode.NOT_LOGIN.getMes(), null);
		}
		Course selectById = courseMapper.selectById(courseId);
		if(selectById==null) {
			return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(),"课程不存在",null);
		}
		if("0".equals(collection)) {
			QueryWrapper<CourseCollection> wrapper=new QueryWrapper<CourseCollection>();
			wrapper.eq("user_id", loginInfo.getId());
			wrapper.eq("course_id", courseId);
			courseCollectionMapper.delete(wrapper);
		}else {
			CourseCollection entity=new CourseCollection();
			entity.setCourseId(courseId);
			entity.setUserId(loginInfo.getId());
			entity.setCreateTime(LocalDateTime.now());
			courseCollectionMapper.insert(entity);
		}
		return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(),null,null);
	}
	
	
	@ApiOperation(value = "用户上传头像", notes = "")
	@GetMapping("/user/uploadHead")
	public Result<String> uploadHead(@RequestParam("file") MultipartFile file,HttpServletRequest request){
		UserInfo loginInfo = UserInfoUtil.getLoginInfo(UserInfo.class, redisUtil, request);
		if(loginInfo==null) {
			return ResultUtil.data(ResultCode.NOT_LOGIN.getCode(),ResultCode.NOT_LOGIN.getMes(), null);
		}
		if(file.isEmpty()){
            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "上传文件不能为空", null);
        }else if(!FileType.hasKey("USER_HEAD")) {
        	return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "文件类型不存在", null);
        }
		String bucketName="static";
        Result<String> upload = ossService.upload(bucketName, "UserHead",file);
        if(ResultCode.RESULT_SUCCESS.getCode().equals(upload.getCode())){
        	upload.setData("http://127.0.0.1:9000"+upload.getData());
        	return upload;
        }
        
        
        return upload;
	}
	
	
	@ApiOperation(value = "用户交易列表", notes = "")
	@GetMapping("/user/transaction/record")
	public Result<PageInfo<UserTransactionRecord>> userList(
			@ApiParam("") @RequestParam(value = "pageNum", required = false) Integer pageNum,
			@ApiParam("") @RequestParam(value = "pageSize", required = false) Integer pageSize,
			HttpServletRequest request){
		UserInfo loginInfo = UserInfoUtil.getLoginInfo(UserInfo.class, redisUtil, request);
		if (loginInfo == null) {
			return ResultUtil.data(ResultCode.NOT_LOGIN.getCode(), ResultCode.NOT_LOGIN.getMes(), null);
		}
		if(pageNum==null||pageSize==null) {
			pageNum=1;
			pageSize=10;
		}
		Page<UserTransactionRecord> page=new Page<UserTransactionRecord>(pageNum,pageSize);
		IPage<UserTransactionRecord> info = transactionRecordMapper.selectUserTransactionRecord(page,loginInfo.getId());
		PageInfo<UserTransactionRecord> data = PageUtil.data(info.getPages(), info.getCurrent(), info.getTotal(), info.getRecords());
		return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(),null, data);
	}
	
	
	@ApiOperation(value = "获取会员价格", notes = "")
	@GetMapping("/user/course/member")
	public Result<String> getMember(HttpServletRequest request){
		UserInfo loginInfo = UserInfoUtil.getLoginInfo(UserInfo.class, redisUtil, request);
		if (loginInfo == null) {
			return ResultUtil.data(ResultCode.NOT_LOGIN.getCode(), ResultCode.NOT_LOGIN.getMes(), null);
		}
		QueryWrapper<com.zdzx.model.service.base.vo.SystemConfig> queryWrapper=new QueryWrapper<com.zdzx.model.service.base.vo.SystemConfig>();
		queryWrapper.eq("`key`",SystemConfigType.MEMBER_PRICE);
		List<com.zdzx.model.service.base.vo.SystemConfig> list = systemConfigMapper.selectList(queryWrapper);
		if(list!=null&&list.size()>0)
			return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(),null, list.get(0).getValue());
		return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), null,null);
	}
	
	
	
	


}
